import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NzMessageService, NzModalRef, UploadFile } from 'ng-zorro-antd';
import { FormBuilder, FormControl, FormGroup,  Validators } from '@angular/forms';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { UtilService } from '@core/services/util.service';
import { Base64Service } from '@core/services/base64.service';

@Component({
  selector: 'app-user-add',
  templateUrl: './user-add.component.html',
  styles: []
})
export class UserAddComponent implements OnInit {
  @ViewChild('treedom',{ static: false }) treedom:any;
  pIdList:any[]=[];
  value: any ;
  validateForm!: FormGroup;
  showForm=true;
  isLoading:boolean=false;
  _param:any;
  show=false;
  cardNo:string;
  nodes=[];
  timeout:any="";


  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }
 
  submitForm(data) {
    console.log(data);
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
      if(this.validateForm.controls[key].invalid){
        return;
      }
    }
    let nodes=this.treedom.getCheckedNodeList();
    if(nodes.length == 0){
      this.msg.error("请选择楼栋!");
      return;
    }
    let list= this.getCheckedNodes(nodes);
    let pIdArr=Array.from(new Set(this.pIdList));
    let houseManagerList=[];
    for(let item of pIdArr){
      let obj={
        houseId:item,
        roomId:""
      }
      let roomList=[];
      for(let current of list){
        if(item == current.pId){
          roomList.push(current.id);
        }
      }
      obj.roomId=roomList.join(",");
      houseManagerList.push(obj);
    }
    const body: any = data;
    body.hoseManagerList=houseManagerList;
    this.http.post("/core/person/qrPeopleRegister",body).subscribe((res:any) => {
      console.log(res)
      if (res.status === '200') {
        this.msg.success('操作成功');
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })
}

//扁平化树形数据
getCheckedNodes(checkedNodeList:any){
  let that=this;
  let list=[];
  this.pIdList=[];
  for(let item of checkedNodeList){
    if(item.origin.pId != ""){
     list.push({
        "id":item.origin.id,
        "pId":item.origin.pId
      })
      that.pIdList.push(item.origin.pId);
    }
    if(item.origin.children && item.origin.children.length > 0){
      for(let current of item.origin.children){
        list.push({
          "id":current.id,
          "pId":current.pId
        })
        that.pIdList.push(current.pId);
      }
    }
  }
  return list;
}

constructor(
  private api: ApiService,
  private http: HttpClient,
  private msg: NzMessageService,
  private modalRef: NzModalRef,
  private util: UtilService,
  private base64: Base64Service,
  private fb: FormBuilder
) {  }

  ngOnInit(): void {
    let that=this;
    // this.getHouses("");
    this.validateForm = this.fb.group({
      infoName: [null, [Validators.required]],
      infoPeopleType: ["", [Validators.required]],
      infoMobile:["",[Validators.required,Validators.pattern(/^1\d{10}$/)]],
    });
  }

  ngOnDestroy(){
  }
  onKey(event){
    let fn=this.debounce(this.getHouses,1000,event.target.value)
    fn()
  }
  debounce(fn,wait,data){
    const self=this
    return ()=>{
      if(self.timeout) clearTimeout(self.timeout)
      self.timeout=setTimeout(()=>{
        fn.call(self,data)
      },wait)
    }
  }
  //获取楼栋房间列表
  getHouses(val): void{
    this.isLoading = true
    this.http.post(this.api.manager.queryUnitHouse.url,{"areaParentAllName":val}).subscribe( (res:any) => {
      console.log(res);
      if (res.status === '200' && res.data && res.data.list.length > 0) {
        let list=[];
        for(let item of res.data.list){
          list.push({
            key:item.id,
            pId:item.areaId == undefined ? "" : item.areaId,
            title:item.areaParentAllName,
            id:item.id,
            value:item.id
          })
          for(let current of item.roomList){
            list.push({
              key:current.id,
              pId:current.areaId,
              title:""+current.roomNumber,
              id:current.id,
              value:current.id
            })
          }
        }
        // console.log(this.util.getTreeNodeOption(list))
        this.nodes=this.util.getTreeNodeOption(list);

        // let span = document.getElementsByClassName("ant-select-not-found")[0]
        // let nzTree = document.querySelector("nz-tree")\
       
        document.getElementById('tree').click()
          setTimeout(() => {
            document.getElementById('tree').click();
          }, 50);
          
      }
      this.isLoading=false;
     
    })
  }
}
